﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using PMPUtils.Form;
using PMPUtils.DB;
using PMPUtils.Documentation;
using PMPUtils.Goals;
using PMPUtils.Resources;

namespace PMP.Operations
{
    public partial class DetailDesignManagement : System.Web.UI.Page
    {
        #region System
        protected void Page_Load(object sender, EventArgs e)
        {
            FormUtil.Authenticate(Session, Response);

            if (!IsPostBack)
            {
                txtGoalID.Text = Request.Params["GOAL"];
                //txtAuthor.Text = Request.Params["AUTHOR"];

                // Read the latest detail design
                try
                {
                    // Bind the goal description
                    txtGoal.Text = GoalsOperator.ReadGoalDesc(txtGoalID.Text.Trim());
                    txtAuthor.Text = FormUtil.GetSessionUserName(Session);

                    String detailDesign = ReadDesignByGoalID(txtGoalID.Text);
                    ftbDetailDesign.Text = detailDesign;

                    RefreshGridViews();
                }
                catch (InvalidOperationException ex)
                {
                    Messenger.Show(Response, "Error: " + ex.Message);
                    return;
                }
            }
        }
        #endregion

        #region Events
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                InsertDetailDesign(0);
            }
            catch (InvalidOperationException ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            RefreshGridViews();
        }

        protected void btnReview_Click(object sender, EventArgs e)
        {
            try
            {
                InsertDetailDesign(1);
            }
            catch (InvalidOperationException ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            RefreshGridViews();

            // Submit to Review
            PopupForm submitToReview = new PopupForm(Response, "DetailDesignManagement-Review.aspx?GOAL=" + txtGoalID.Text.Trim(), "DetailDesignManagement-Review", "225", "350", "350", "200");
            submitToReview.Popup();
        }

        protected void grvReviewHistory_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            // Convert the row index stored in the CommandArgument
            // property to an Integer.
            int index = Convert.ToInt32(e.CommandArgument);

            // Retrieve the row that contains the button clicked 
            // by the user from the Rows collection.
            GridViewRow row = grvReviewHistory.Rows[index];

            String goal_id = GridViewOperator.GetCellStringValue(grvReviewHistory, row, "goal_id");
            String author = GridViewOperator.GetCellStringValue(grvReviewHistory, row, "author");

            int ID = GridViewOperator.GetCellIntValue(grvRevisionHistory, row, "ID");
            String detailDesign = String.Empty;
            try
            {
                detailDesign = ReadDesign(ID);
            }
            catch (InvalidOperationException ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            if (e.CommandName.Equals("DetailDesignDetails"))
            {
                txtGoalID.Text = goal_id;
                txtAuthor.Text = author;
                ftbDetailDesign.Text = detailDesign;
            }
        }

        protected void grvRevisionHistory_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            // Convert the row index stored in the CommandArgument
            // property to an Integer.
            int index = Convert.ToInt32(e.CommandArgument);

            // Retrieve the row that contains the button clicked 
            // by the user from the Rows collection.
            GridViewRow row = grvRevisionHistory.Rows[index];

            String goal_id = GridViewOperator.GetCellStringValue(grvRevisionHistory, row, "goal_id");
            String author = GridViewOperator.GetCellStringValue(grvRevisionHistory, row, "author");

            int ID = GridViewOperator.GetCellIntValue(grvRevisionHistory, row, "ID");
            String detailDesign = String.Empty;
            try
            {
                detailDesign = ReadDesign(ID);
            }
            catch (InvalidOperationException ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            if (e.CommandName.Equals("DetailDesignDetails"))
            {
                txtGoalID.Text = goal_id;
                txtAuthor.Text = author;
                ftbDetailDesign.Text = detailDesign;
            }
        }
        #endregion

        #region Privates
        private string ReadDesignByGoalID(string goal_id)
        {
            String detailDesign = String.Empty;

            String strQueryDesign = "select top 1 design from detaildesign where goal_id = '" + goal_id + "' order by ID desc";
            DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
            DataTable dtDesign = localOperator.Read(strQueryDesign);

            foreach (DataRow row in dtDesign.Rows)
            {
                if (row["design"] != null && !row["design"].ToString().Equals(String.Empty))
                {
                    detailDesign = row["design"].ToString();
                }
            }

            detailDesign = detailDesign.Replace('\"', '\'');

            return detailDesign;
        }

        private string ReadDesign(int ID)
        {
            String detailDesign = String.Empty;

            String strQueryDesign = "select design from DetailDesign where ID = " + ID;
            DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
            DataTable dtDetailDesign = localOperator.Read(strQueryDesign);

            foreach (DataRow row in dtDetailDesign.Rows)
            {
                if (row["design"] != null && !row["design"].ToString().Equals(String.Empty))
                {
                    detailDesign = row["design"].ToString();
                }
            }

            detailDesign = detailDesign.Replace('\"', '\'');

            return detailDesign;
        }

        private void InsertDetailDesign(int to_review)
        {
            String goalID = txtGoalID.Text.Trim();
            String author = FormUtil.GetSessionUserName(Session);
            String detailDesign = ftbDetailDesign.Text.Trim();

            detailDesign = detailDesign.Replace('\'', '\"');

            int revision = GetNewRevision(goalID);

            String strInsertScope = "insert into detaildesign (author, goal_id, rev, design, to_review) values " +
                "('" + author + "','" + goalID + "'," + revision + ",'" + detailDesign + "'," + to_review + ")";
            DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
            localOperator.Update(strInsertScope);
        }

        private void RefreshGridViews()
        {
            DataTable dtReviews = DetailDesignOperator.ReadDetailDesignsInReview(txtGoalID.Text.Trim());
            grvReviewHistory.DataSource = dtReviews.DefaultView;
            grvReviewHistory.DataBind();

            DataTable dtRevision = DetailDesignOperator.ReadDetailDesignsNotInReview(txtGoalID.Text.Trim());
            grvRevisionHistory.DataSource = dtRevision.DefaultView;
            grvRevisionHistory.DataBind();
        }

        private int GetNewRevision(String goal_id)
        {
            int revision = 1;

            String strQueryMaxRevision = "select isnull(max(rev), 0) + 1 as MaxRev from detaildesign where goal_id = '" + goal_id + "'";
            DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
            DataTable dtMaxRevision = localOperator.Read(strQueryMaxRevision);

            foreach (DataRow row in dtMaxRevision.Rows)
            {
                if (row["MaxRev"] != null && !row["MaxRev"].ToString().Equals(String.Empty))
                {
                    revision = Convert.ToInt32(row["MaxRev"].ToString());
                }
            }

            return revision;
        }
        #endregion

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                RefreshGridViews();
            }
            catch (InvalidOperationException ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }
        }



        protected void btnApprove_Click(object sender, EventArgs e)
        {
            try
            {
                InsertDetailDesign(1);

                RefreshGridViews();

                // Send notification
                String subject = "Detail Design Approved: " + GoalsOperator.ReadGoalDesc(txtGoalID.Text);
                Email(subject);
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            Messenger.Show(Response, "Approved.");
        }

        protected void btnSuggest_Click(object sender, EventArgs e)
        {
            try
            {
                InsertDetailDesign(0);

                RefreshGridViews();

                // Send notification
                String subject = "Detail Design Suggest: " + GoalsOperator.ReadGoalDesc(txtGoalID.Text);
                Email(subject);
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            Messenger.Show(Response, "Suggestions Sent.");
        }

        protected void Email(String subject)
        {
            String userName = FormUtil.GetSessionUserName(Session);
            String ownerID = GoalsOperator.ReadGoalOwner(txtGoalID.Text.Trim());
            String owner = ResourceOperator.ReadResourceName(ownerID);
            String body = "http://bs-pc-664:9090/Documentation/DetailDesignManagement.aspx?GOAL=" + txtGoalID.Text.Trim();

            DetailDesignOperator.SubmitToReview(owner, subject, userName, body);
        }

        protected void btnQualityStatement_Click(object sender, EventArgs e)
        {
            // Submit to Review
            PopupForm popup = new PopupForm(Response, "DetailDesignManagement_QualityStatement.aspx", "DetailDesignManagement_QualityStatement", "1000", "450", "50", "100");
            popup.Popup();
        }
    }
}
